#include <QApplication>
#include "databasemanager.h"
#include "backendservice.h"
#include "websocketserver.h"
#include "runtimefilesystemwatcher.h"
#include "systemtraymanager.h"
#include <QDebug>
#include <QStandardPaths>
#include <QDir>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // 创建全局实例（使用 new 确保对象生命周期）
    DatabaseManager *databaseManager = new DatabaseManager(&app);
    BackendService *backendService = new BackendService(&app);
    WebSocketServer *webSocketServer = new WebSocketServer(&app);
    RuntimeFileSystemWatcher *runtimeFileSystemWatcher = new RuntimeFileSystemWatcher(&app);
    SystemTrayManager *systemTrayManager = new SystemTrayManager(&app);
    
    // 启动 WebSocket 服务器（监听 9038 端口）
    if (webSocketServer->startServer(9038)) {
        qDebug() << "WebSocket 服务器已成功启动在端口 9038";
    } else {
        qDebug() << "WebSocket 服务器启动失败";
    }
    
    // 启动 RuntimeFileSystemWatcher 监听 runtime 目录
    runtimeFileSystemWatcher->startWatching();
    qDebug() << "RuntimeFileSystemWatcher 已启动，监听目录:" << runtimeFileSystemWatcher->getRuntimeDirectory();
    
    // 设置数据库管理器到BackendService
    backendService->setDatabaseManager(databaseManager);
    
    // 设置数据库管理器到RuntimeFileSystemWatcher
    runtimeFileSystemWatcher->setDatabaseManager(databaseManager);
    
    // 设置 BackendService 到 RuntimeFileSystemWatcher
    runtimeFileSystemWatcher->setBackendService(backendService);
    
    // 设置 WebSocketServer 到 RuntimeFileSystemWatcher
    runtimeFileSystemWatcher->setWebSocketServer(webSocketServer);
    
    // 设置 BackendService 到 WebSocketServer
    webSocketServer->setBackendService(backendService);
    
    // 初始化数据库：设置 workDirectory 为 HOME/.myapps
    QString homePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
    if (homePath.isEmpty()) {
        qDebug() << "无法获取用户主目录";
    } else {
        // 构建工作目录路径：HOME/.myapps
        QString workDirectory = QDir(homePath).filePath(".myapps");
        
        // 确保目录存在
        QDir dir;
        if (!dir.exists(workDirectory)) {
            if (dir.mkpath(workDirectory)) {
                qDebug() << "成功创建工作目录:" << workDirectory;
            } else {
                qDebug() << "创建工作目录失败:" << workDirectory;
            }
        } else {
            qDebug() << "工作目录已存在:" << workDirectory;
        }
        
        // 设置用户工作目录并初始化数据库
        if (databaseManager->setUserWorkDirectoryAndDatabase(workDirectory)) {
            qDebug() << "数据库初始化成功，工作目录:" << workDirectory;
        } else {
            qDebug() << "数据库初始化失败，工作目录:" << workDirectory;
        }
    }
    
    // 连接BackendService的信号到DatabaseManager
    QObject::connect(backendService, &BackendService::syncDisksData, 
                     databaseManager, &DatabaseManager::syncDisksFromJson);
    QObject::connect(backendService, &BackendService::syncFoldersData, 
                     databaseManager, &DatabaseManager::syncFoldersFromJson);
    QObject::connect(backendService, &BackendService::syncFilesData, 
                     databaseManager, &DatabaseManager::syncFilesFromJson);
    QObject::connect(backendService, &BackendService::commitFileSuccess, 
                     databaseManager, [databaseManager](const QString &fileId) {
                         qDebug() << "文件提交成功，更新文件状态为已同步，文件ID:" << fileId;
                         databaseManager->updateFileStatus(fileId, 1);
                     });
    

    // 设置托盘图标提示信息
    systemTrayManager->setTrayToolTip("HiAPP-lite - 文件浏览器状态跟踪器");
    
    // 连接托盘图标的退出信号
    QObject::connect(systemTrayManager, &SystemTrayManager::quitRequested,
                     &app, &QApplication::quit);
    
    // 应用启动后直接显示托盘图标（最小化到托盘）
    systemTrayManager->showTrayIcon();
    qDebug() << "应用已启动，托盘图标已显示";

    return app.exec();
}
